package com.ruoyi.framework.config

import java.util.HashMap
import javax.servlet.DispatcherType
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import com.ruoyi.common.filter.RepeatableFilter
import com.ruoyi.common.filter.XssFilter
import org.apache.commons.lang3.StringUtils
import javax.servlet.Filter


/**
 * Filter配置
 *
 * @author ruoyi
 */
@Configuration
open class FilterConfig {
    @Value("\${xss.excludes}")
    private val excludes: String? = null

    @Value("\${xss.urlPatterns}")
    private val urlPatterns: String? = null

    @Bean
    @ConditionalOnProperty(value = ["xss.enabled"], havingValue = "true")
    open fun xssFilterRegistration(): FilterRegistrationBean<*> {
        val registration = FilterRegistrationBean<Filter>()
        registration.setDispatcherTypes(DispatcherType.REQUEST)
        registration.filter = XssFilter()
        registration.addUrlPatterns(*StringUtils.split(urlPatterns, ","))
        registration.setName("xssFilter")
        registration.order = FilterRegistrationBean.HIGHEST_PRECEDENCE
        val initParameters: MutableMap<String, String?> = HashMap()
        initParameters["excludes"] = excludes
        registration.initParameters = initParameters
        return registration
    }

    @Bean
    open fun someFilterRegistration(): FilterRegistrationBean<*> {
        val registration = FilterRegistrationBean<Filter>()
        registration.filter = RepeatableFilter()
        registration.addUrlPatterns("/*")
        registration.setName("repeatableFilter")
        registration.order = FilterRegistrationBean.LOWEST_PRECEDENCE
        return registration
    }
}
